// Copyright (c) 2025, 大连理工大学 (Dalian University of Technology)
//
// Licensed under the Mulan PSL v2.
// You can use this file according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of the License at
//
//     http://license.coscl.org.cn/MulanPSL2
//
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. SEE THE MULAN PSL v2
// FOR MORE DETAILS.

#include "DBManager/Repository/HDF5/Input/Property/PBARLRepository.h"

#include "DBManager/IRepository/Input/Property/IPropertySummaryRepository.h"
#include "DBManager/Repository/HDF5/Base/HDF5RepositoryMacro.h"

#include "PBARLRepository.h"

HDF5_REG_REPOSITORY (PBARLRepository)

using namespace SG::DBManager::HDF5;

using SG::DataStructure::FEM::PBARLData;
using SG::DBManager::HDF5::PBARL::IDENTITY;

PBARLRepository::PBARLRepository (HDF5Database& database) : MainlyRepositoryBase<PBARLData> (database)
{}

void PBARLRepository::InitialDatasetInfo ()
{
    RegisterIndex ("/OWN/INDEX/INPUT/PROPERTY/PBARL", IndexDataset, GetType ());
    RegisterTableInfo<IDENTITY> ("/SG/INPUT/PROPERTY/PBARL/IDENTITY", MainDataset);
    RegisterTableInfo<SG::DataStructure::Common::Real> ("/SG//INPUT/PROPERTY/PBARL/INFO", INFO);

    // 连接信号槽 当调用汇总的时候，将已有的缓存信息全部都持久化到HDF5文件中。
    GetDatabase ().GetHDF5Hub()->m_propertySummarySignal.connect ([this] { Sort (); });
}

void PBARLRepository::DumpWriteCahce ()
{
    auto& writeStorage = this->GetMainCache ().m_writeStorage;

    // 设置为无顺序
    this->GetMainDatasetInfo ().SetIsSequential (false);

    // 主表数据
    std::vector<IDENTITY> IDENTITYData{};
    // 附表数据
    std::vector<SG::DataStructure::Common::Real> INFOData;

    // 转换为nastran格式数据
    OwnToNastran (writeStorage, IDENTITYData, INFOData);

    // 写出主表
    WriteData (MainDataset, IDENTITYData);
    // 写出附表
    WriteData (INFO, INFOData);
    // 更新Index表
    WriteIndexData (this->GetIndexDatasetInfo (), writeStorage);

    // 清空缓存
    writeStorage.clear ();
}

std::vector<PBARLRepository::DataType>*  PBARLRepository::LoadReadCache (std::size_t loadIndex)
{
    // 读取范围内的主表信息
    std::vector<IDENTITY> IDENTITYData;
    this->LoadMainMetadata (loadIndex, IDENTITYData);

    if (IDENTITYData.empty ())
    {
        return nullptr;
    }

    // 读取范围内的附表信息
    std::vector<SG::DataStructure::Common::Real> INFOData;
    LoadSecondaryMetadata (IDENTITYData, INFO_POS, INFO_LEN, INFO, INFOData);

    auto* cacheVector = m_cacheHelper.LookupOrCreateVector<DataType> (GetMainCache ().m_readCacheKey, IDENTITYData.size ());
    NastranToOwn (IDENTITYData, INFOData, *cacheVector);
    return cacheVector;
}

void PBARLRepository::SortData ()
{
    std::vector<PBARL::IDENTITY> IDENTITYData;
    GetDataset (MainDataset).read (IDENTITYData);

    if (IDENTITYData.empty ())
    {
        GetMainDatasetInfo ().SetIsSequential (true);
        return;
    }

    std::vector<SG::DataStructure::Common::Real> INFOData;
    GetDataset (INFO).read (INFOData);

    // 将所有数据转换
    std::vector<PBARLData> AllData{};
    NastranToOwn (IDENTITYData, INFOData, AllData);
    // 排序
    std::sort (AllData.begin (), AllData.end ());

    OwnToNastran (AllData, IDENTITYData, INFOData, true);

    // 写出数据至文件
    GetDataset (MainDataset).write (IDENTITYData);
    GetDataset (INFO).write (INFOData);

    // 重写索引
    RewriteIndexData (AllData);

    // 设置为已顺序
    GetMainDatasetInfo ().SetIsSequential (true);
}

std::vector<PBARLData> PBARLRepository::GetAllData ()
{
    Sort ();

    std::vector<PBARLData> result;

    std::vector<PBARL::IDENTITY> IDENTITYData;
    GetDataset (MainDataset).read (IDENTITYData);

    if (IDENTITYData.empty ())
    {
        return result;
    }

    std::vector<SG::DataStructure::Common::Real> INFOData;
    GetDataset (INFO).read (INFOData);

    // 将所有数据转换
    NastranToOwn (IDENTITYData, INFOData, result);

    return result;
}

void PBARLRepository::OwnToNastran (std::vector<PBARLData>&                            own,
                                    std::vector<IDENTITY>& _OUT                        IDENTITYData,
                                    std::vector<SG::DataStructure::Common::Real>& _OUT INFOData,
                                    bool                                               isSort)
{
    INFOData.clear ();
    IDENTITYData.clear ();
    IDENTITYData.reserve (own.size ());

    // 获取已有数据条数，主要是放在主表的POS字段
    // 如果是重新排序的时候，Pos都是从0 开始的
    size_t INFOCount = isSort ? 0 : this->GetDatasetInfo (INFO).GetRowCount ();

    // OwnIdent 代表咱们自己的数据结构
    // NasIdent 代表nastran的数据结构
    for (auto& OwnIdent : own)
    {
        // 写入附表
        INFOData.insert (INFOData.end (), OwnIdent.m_dimension.begin (), OwnIdent.m_dimension.end ());
        INFOData.push_back (OwnIdent.m_nsm);  // ※

        const size_t len = OwnIdent.m_dimension.size () + 1;

        // 写入IDENTITY
        IDENTITY identity{};
        identity.PID = OwnIdent.m_id;
        identity.MID = OwnIdent.m_mId;
        memcpy (identity.GROUP, OwnIdent.m_group, 8);
        memcpy (identity.TYPE, OwnIdent.m_type, 8);
        identity.INFO_POS  = static_cast<SG::DataStructure::Common::I64> (INFOCount);
        identity.INFO_LEN  = static_cast<SG::DataStructure::Common::I64> (len);
        identity.DOMAIN_ID = OwnIdent.m_domainId;

        IDENTITYData.emplace_back (identity);

        INFOCount += len;  // 加1是因为nsm
    }
}

void PBARLRepository::NastranToOwn (std::vector<IDENTITY>&                        IDENTITYData,
                                    std::vector<SG::DataStructure::Common::Real>& INFOData,
                                    std::vector<PBARLData>& _OUT                  own)
{
    own.clear ();
    own.reserve (IDENTITYData.size ());

    // 代表初始的Index 位置, 因为数据有可能是截取了附表的一部分，所有主表中根据POS找的时候需要对应一下，
    // 比如第一个主表数据中POS字段为10000， 附表的vector的数据 就是从附表中的第10000个开始对应的 也就是Index==0的
    const SG::DataStructure::Common::I64 infoIndex = IDENTITYData[0].INFO_POS;

    for (auto&& NasIdent : IDENTITYData)
    {
        PBARLData data;
        data.m_id  = NasIdent.PID;
        data.m_mId = NasIdent.MID;
        memcpy (data.m_group, NasIdent.GROUP, 8);
        memcpy (data.m_type, NasIdent.TYPE, 8);
        data.m_domainId = NasIdent.DOMAIN_ID;
        // assign 清除矢量并将指定的元素复制到该空矢量。
        data.m_dimension.assign (INFOData.begin () + NasIdent.INFO_POS - infoIndex,
                                 INFOData.begin () + NasIdent.INFO_POS + NasIdent.INFO_LEN - infoIndex - 1);
        data.m_nsm = INFOData[NasIdent.INFO_POS + NasIdent.INFO_LEN - 1];

        own.emplace_back (data);
    }
}
